package com.guxiaotu.config;

import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author Gu Yuanhua
 * created time 2018/8/3 20:50
 */
@Configuration
@EnableTransactionManagement
@MapperScan("com.guxiaotu.mapper")
public class JdbcConfig {

    private final DataSource dataSource;

    @Autowired
    public JdbcConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 开启事务管理
     */
    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 注册SqlSessionFatory，mybatis默认识别sqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean ();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();

    }


    // 使用@MapperScan来代替
/*
    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer ();
        // 扫描包com.guxiaotu.mapper
        mapperScannerConfigurer.setBasePackage ("com.guxiaotu.mapper");
        // 传字符串而不是实际sqlSessionFactory对象
        mapperScannerConfigurer.setSqlSessionFactoryBeanName ("sqlSessionFactory");
        return mapperScannerConfigurer;
    }
*/

}
